package com.teacher.client;

import com.teacher.entity.Student;
import com.teacher.entity.Teacher;
import com.teacher.util.Datas;
import com.teacher.util.SysConstants;
import com.teacher.util.Tools;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * ClientBiz--bdqnPractice
 *
 * @author: Jovi
 * @createTime: 2017-09-25 16:53
 **/
public class ClientBiz {

    Socket socket = null;

    ObjectOutputStream oos = null;

    ObjectInputStream ois = null;

    private void init() {
        String hostName = Tools.getValue(SysConstants.SYS_HOST.getName());
        int port = Integer.valueOf(Tools.getValue(SysConstants.SYS_LISTENERPORT.getName()));

        try {
            socket = new Socket(hostName, port);
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Datas doLogin(String userName, String password) {

        init();
        Teacher teacher = new Teacher();
        teacher.setUserName(userName);
        teacher.setPassWord(password);

        Datas datas = new Datas();
        datas.setTeacher(teacher);
        datas.setFlag(SysConstants.SYS_LOGIN.getName());

        return getDatas(datas);

    }

    public Datas doFind(int teacherId) {

        init();
        Datas datas = new Datas();

        datas.setFlag(SysConstants.SYS_FIND.getName());
        Teacher teacher = new Teacher();
        teacher.setId(teacherId);
        datas.setTeacher(teacher);
        return getDatas(datas);
    }


    public Datas doUpdate(int stuId,String comments) {

        init();
        Datas datas = new Datas();
        datas.setFlag(SysConstants.SYS_UPDATE.getName());

        Student student = new Student();
        student.setStuId(stuId);
        student.setComment(comments);
        datas.setStudent(student);
        return getDatas(datas);
    }


    public Datas doDelete(int stuId) {

        init();
        Datas datas = new Datas();
        datas.setFlag(SysConstants.SYS_DELETE.getName());

        Student student = new Student();
        student.setStuId(stuId);
        datas.setStudent(student);
        return getDatas(datas);
    }

    private void closeSocket() {
        try {
            oos.close();
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Datas getDatas(Datas datas) {
        try {
            oos.writeObject(datas);
            datas = (Datas) ois.readObject();
            return datas;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            closeSocket();
        }
        return null;
    }
}
